package com.tdrc.common.controller;

import com.alibaba.druid.util.StringUtils;
import com.tdrc.common.beans.ResultCode;
import com.tdrc.common.service.FileService;
import com.tdrc.common.util.CommonUtil;
import com.tdrc.common.util.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dpf
 * @version 1.0
 * @date 2020-5-12 17:23
 * @instruction ...
 */
@Controller
@RequestMapping("/file")
@CrossOrigin
public class FileController extends BaseController {
    @Resource
    private FileService fileService;
    @Value("${file.basePath}")
    private   String  FILE_BASE_PATH;
    /**
     * 多文件上传
     * @param files
     * @param rootPath
     * @return
     */
    @RequestMapping(value = "/upload")
    @ResponseBody
    public Object uploadFile(@RequestParam("file") MultipartFile[] files, String rootPath) {
        rootPath = StringUtils.isEmpty(rootPath) ? FILE_BASE_PATH : rootPath;
        File f = new File(rootPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        String separator=files.length>1?";":"";
        Map<String,Object> result = new HashMap<>(16);
        if (files != null && files.length != 0) {
            StringBuffer savePath=new StringBuffer() ;
            StringBuffer realFileName = new StringBuffer();
            for (MultipartFile file : files) {
                try {
                    realFileName.append(file.getOriginalFilename()).append(separator);
                    String saveFileName = CommonUtil.getUploadFileName(CommonUtil.getSuffix(file.getOriginalFilename()));
                    file.transferTo(new File(rootPath + saveFileName));
                    savePath.append(saveFileName).append(separator);;
                } catch (Exception e) {
                    logger.error("文件上传失败");
                    e.printStackTrace();
                    return new JsonResult(ResultCode.FILE_UPLOAD_FAILURE);
                }
            }
            result.put("savePath",savePath);
            result.put("realFileName",realFileName);
            return new JsonResult(ResultCode.OK,result);
        }else{
            return new JsonResult(ResultCode.FILE_UPLOAD_EMPTY);
        }
    }
}
